package world.xuewei.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import world.xuewei.component.ImageConstants;
import world.xuewei.dao.CommodityDao;
import world.xuewei.model.entity.*;
import world.xuewei.service.ClassifyService;
import world.xuewei.service.CommodityService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import world.xuewei.service.MerchantInfoService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 商品表(Commodity)表控制层
 *
 * @author makejava
 * @since 2024-11-16 15:40:05
 */
@Slf4j
@RestController
@RequestMapping("/commodity")
public class CommodityController {
    /**
     * 服务对象
     */
    @Resource
    private CommodityService commodityService;

    @Resource
    private ClassifyService classifyService;

    @Resource
    private CommodityDao commodityDao;

    @Resource
    private MerchantInfoService merchantInfoService;

    // 获取首页信息商品
    @GetMapping("/index")
    public R getallcommodity() {
        try {

            // 获取销量前三的商品
            List<Commodity> topSales = commodityService.getTopSalesCommodities();
            // 轮播图1
            List<Map<String, Object>> list = new ArrayList<>();
            // 使用ConcurrentHashMap替代HashMap
            Map<String, Object> carousel1 = new ConcurrentHashMap<>();
            carousel1.put("url", ImageConstants.Carousel.CAROUSEL_1);
            carousel1.put("sort", 1);
            list.add(carousel1);

            Map<String, Object> carousel2 = new ConcurrentHashMap<>();
            carousel2.put("url", ImageConstants.Carousel.CAROUSEL_2);
            carousel2.put("sort", 2);
            list.add(carousel2);

            Map<String, Object> carousel3 = new ConcurrentHashMap<>();
            carousel3.put("url", ImageConstants.Carousel.CAROUSEL_3);
            carousel3.put("sort", 3);
            list.add(carousel3);

            Map<String, Object> carousel4 = new ConcurrentHashMap<>();
            carousel4.put("url", ImageConstants.Carousel.CAROUSEL_4);
            carousel4.put("sort", 4);
            list.add(carousel4);

            return R.ok()
                    .message("登录成功")
                    .data("轮播图信息", list)
                    .data("推荐", topSales);
        } catch (Exception e) {
            return R.error().message(e.getMessage());
        }
    }

    //根据商品id获取商品信息
    @GetMapping("/detail/{id}")
    public R getDetail(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            return R.error().message("无效的商品ID");
        }

        // 1. 获取商品基本信息
        Commodity commodity = commodityService.queryById(id);
        if (commodity == null) {
            return R.error().message("商品不存在");
        }

        // 2. 查询商品规格信息
        Map<String, Object> result = new HashMap<>();
        result.put("commodity", commodity);

        // 3. 查询商品可选规格
        List<Map<String, Object>> specifications = commodityService.getSpecifications(id);
        result.put("specifications", specifications);

        return R.ok().data(result);
    }

    // 商家添加新的商品
    @PostMapping("/addproduct")
    public R addProduct(@RequestBody Commodity commodity,HttpServletRequest request) {
        try {
            // 参数校验
            // 1. 获取当前登录商户ID
            String userIdStr = (String)request.getAttribute("userId");
            if (userIdStr == null) {
                return R.error().message("用户未登录 or 携带token请求");
            }
            Long userId = Long.parseLong(userIdStr);
            commodity.setMerchantId(userId);

            if (commodity == null) {
                return R.error().message("参数不能为空");
            }
            if (commodity.getMerchantId() == null || commodity.getMerchantId() <= 0 ) {
                return R.error().message("商户ID不能为空,或者是无效的商户ID");
            }
            if (commodity.getClassifyId() == null || commodity.getClassifyId() <= 0 ) {
                return R.error().message("商品分类ID不能为空,或者是无效的分类ID");
            }
            // 查看商品分类
            Classify classifyId  = classifyService.queryById(commodity.getClassifyId());
            if(classifyId == null ){
                return R.error().message("没有该商品分类");
            }

            if(!StringUtils.hasText(commodity.getName())){
                return R.error().message("商品名称不能为空");
            }
            // 商品名称限制
            String productName  = commodity.getName();
            if (StringUtils.hasText(commodity.getName())) {
                int length = productName.replaceAll("[^\\x00-\\xff]", "**").length();
                if (length > 30) {
                    return R.error().message("商品名称不能超过30个英文字符或15个汉字");
                }
            }
            if ( commodity.getNowPrice() == null || commodity.getNowPrice().compareTo(BigDecimal.ZERO) <= 0) {
                return R.error().message("销售价格不能为空或无效");
            }
            //插入数据
            boolean success = commodityService.addProduct(commodity);
            return success ?
                    R.ok().message("新增商品成功") :
                    R.error().message("新增商品失败");
        } catch (Exception e) {
            return R.error().message(e.getMessage());
        }
    }



    //根据商品修改商品信息
    @PostMapping("/productInformation")
    public R productInformation(@RequestBody Commodity commodity,HttpServletRequest request)  {
        try {
            if(commodity.getId() == null || commodity.getName() == null || commodity.getNowPrice() == null){
                return R.error().message("商品id,商品名称，现价缺一不可");
            }
            // 商品名称限制
            String productName  = commodity.getName();
            if (StringUtils.hasText(commodity.getName())) {
                int length = productName.replaceAll("[^\\x00-\\xff]", "**").length();
                if (length > 30) {
                    return R.error().message("商品名称不能超过30个英文字符或15个汉字");
                }
            }
            if (commodity.getNowPrice().compareTo(BigDecimal.ZERO) < 0 || commodity.getOriginalPrice().compareTo(BigDecimal.ZERO) < 0 || commodity.getInventory() == null || commodity.getInventory()  < 0 ){
                return R.error().message("原价,现价,库存,不能小于0");
            }
            if (commodity.getStatus() != 0 && commodity.getStatus() != 1){
                return R.error().message("状态码只能是0或者1");
            }
            // 查找商品id是否存在
            Commodity productInformation  = commodityDao.queryById(commodity.getId());
            if(productInformation == null ) {
                return R.error().message("没有该商品");
            }
            // 商品分类
            Classify classifyId  = classifyService.queryById(commodity.getClassifyId());
            if(classifyId == null ){
                return R.error().message("没有该商品分类");
            }
            // 修改成功
            boolean success = commodityService.updateProductInformation(commodity);
            return success ?
                    R.ok().message("修改商品信息成功") :
                    R.error().message("修改商品信息失败");
        }catch (Exception e) {
            return R.error().message(e.getMessage());
        }
    }

    /**
     * 增加商品库存
     * POST /commodity/inventory/add
     */
    @PostMapping("/inventory/add")
    public R addInventory(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            // 1. 获取当前登录商户ID
            String userIdStr = (String) request.getAttribute("userId");
            if (userIdStr == null) {
                return R.error().message("用户未登录 or 携带token请求");
            }
            Long userId = Long.parseLong(userIdStr);

            // 2. 获取请求参数
            Long commodityId = Long.parseLong(params.get("id").toString());
            Integer quantity = Integer.parseInt(params.get("quantity").toString());

            // 3. 验证商品是否属于当前商户
            Commodity commodity = commodityService.queryById(commodityId);
            if (commodity == null) {
                return R.error().message("商品不存在");
            }

            if (!commodity.getMerchantId().equals(userId)) {
                return R.error().message("无权操作此商品");
            }

            // 4. 增加库存
            boolean success = commodityService.addInventory(commodityId, quantity);
            if (success) {
                return R.ok().message("库存增加成功");
            } else {
                return R.error().message("库存增加失败");
            }
        } catch (NumberFormatException e) {
            return R.error().message("参数格式错误");
        } catch (Exception e) {
            return R.error().message("库存增加失败：" + e.getMessage());
        }
    }


    /**
     * 商品下架
     * POST /commodity/offline/{id}
     */
    @PostMapping("/offline/{id}")
    public R offline(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 1. 获取当前登录商户ID
            String userIdStr = (String) request.getAttribute("userId");
            if (userIdStr == null) {
                return R.error().message("用户未登录");
            }
            Long userId = Long.parseLong(userIdStr);

            // 2. 验证商品是否存在
            Commodity commodity = commodityService.queryById(id);
            if (commodity == null) {
                return R.error().message("商品不存在");
            }

            // 3. 验证商品是否属于当前商户
            if (!commodity.getMerchantId().equals(userId)) {
                return R.error().message("无权操作此商品");
            }

            // 4. 执行下架操作
            boolean success = commodityService.offline(id);
            if (success) {
                return R.ok().message("商品下架成功");
            } else {
                return R.error().message("商品下架失败");
            }
        } catch (NumberFormatException e) {
            return R.error().message("参数格式错误");
        } catch (Exception e) {
            return R.error().message("商品下架失败：" + e.getMessage());
        }
    }

    /**
     * 商品上架
     * POST /commodity/online/{id}
     */
    @PostMapping("/online/{id}")
    public R online(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 1. 获取当前登录商户ID
            String userIdStr = (String) request.getAttribute("userId");
            if (userIdStr == null) {
                return R.error().message("用户未登录");
            }
            Long userId = Long.parseLong(userIdStr);

            // 2. 验证商品是否存在
            Commodity commodity = commodityService.queryById(id);
            if (commodity == null) {
                return R.error().message("商品不存在");
            }

            // 3. 验证商品是否属于当前商户
            if (!commodity.getMerchantId().equals(userId)) {
                return R.error().message("无权操作此商品");
            }

            // 4. 执行上架操作
            boolean success = commodityService.online(id);
            if (success) {
                return R.ok().message("商品上架成功");
            } else {
                return R.error().message("商品上架失败");
            }
        } catch (NumberFormatException e) {
            return R.error().message("参数格式错误");
        } catch (Exception e) {
            return R.error().message("商品上架失败：" + e.getMessage());
        }
    }


    /**
     * 收藏/取消收藏
     * POST /commodity/favorite/toggle
     */
    @PostMapping("/favorite/toggle/{commodity_id}")
    public R toggleFavorite(@PathVariable Long commodity_id,HttpServletRequest request) {
        try {
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);
            boolean success = commodityService.addFavorite(
                    userId,
                    commodity_id
            );
            return R.ok().message(success ? "收藏成功" : "取消收藏成功");
        } catch (Exception e) {
            return R.error().message("操作失败：" + e.getMessage());
        }
    }

    /**
     * 查询收藏列表
     * GET /commodity/favorite/list/{userId}
     */
    @GetMapping("/favorite/list")
    public R getFavorites(HttpServletRequest request) {
        try {
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);
            List<Commodity> favorites = commodityService.queryFavorites(userId);
            return R.ok().data("favorites", favorites);
        } catch (Exception e) {
            return R.error().message("查询收藏列表失败：" + e.getMessage());
        }
    }







    /**
     * 分页查询
     *
     * @param commodity   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Commodity>> queryByPage(Commodity commodity, PageRequest pageRequest) {
        return ResponseEntity.ok(this.commodityService.queryByPage(commodity, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Commodity> queryById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(this.commodityService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param commodity 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Commodity> add(Commodity commodity) {
        return ResponseEntity.ok(this.commodityService.insert(commodity));
    }

    /**
     * 编辑数据
     *
     * @param commodity 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Commodity> edit(Commodity commodity) {
        return ResponseEntity.ok(this.commodityService.update(commodity));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Long id) {
        return ResponseEntity.ok(this.commodityService.deleteById(id));
    }

}

